package com.bookcode.controller;


import com.bookcode.entity.*;
import com.bookcode.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Column;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class SignController {

    @Autowired
    SignService signService;
//    @Autowired
//    SignRecorderService signRecorderService;
    @Autowired
    CourseService courseService;
    @Autowired
    CourseStudentService courseStudentService;
    @Autowired
    StudentService studentService;
    @Autowired
    SignRecorderService signRecorderService;
    //根据id找到签到码
    @RequestMapping("/findSingById/{id}")
    public Sign findSignById(@PathVariable("id") Long  id){
       return  signService.findSignById(id);
    }
    //根据课程号找到最新的签到码
    @RequestMapping("/findCodeByCourseId/{courseId}")
    public HttpResult<Sign>findSignsByCourse(@PathVariable("courseId") String courseId){
        HttpResult<Sign> httpResult=new HttpResult<>();
        try {
            httpResult.setData(signService.findSignsByCourse(courseId));
//            System.out.println(signService.findSignsByCourse(courseId));
            httpResult.setStatus("SuccessLy！");
        }catch (Exception e){
            httpResult.setStatus("查找失败");
        }finally {
            return  httpResult;
        }
    }
    //发放签到码，即保存签到码
    @RequestMapping("/AddSignCode/{courseId}")
    public HttpResult save(@PathVariable("courseId") String courseId){
        HttpResult<Sign> httpResult=new HttpResult<>();
      try {
          Sign sign = new Sign();
          sign.setCourseId(courseId);

          String random = UUID.randomUUID().toString().substring(0, 5);
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
          java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
          sign.setSign_key(random);
          sign.setState(true);
          sign.setTime(date);
          System.out.println(sign.toString());
          httpResult.setStatus(sign.toString());
          httpResult.setMessage("添加成功");
          signService.save(sign);
      }catch (Exception e){
          httpResult.setMessage("添加失败");
      }finally {
          return httpResult;
      }
    }
    @Autowired
    QueqinService queqinService;
    //停止签到
    @RequestMapping("/stopSign/{courseId}")
   public HttpResult<Sign>  stopSign(@PathVariable String courseId){
        HttpResult<Sign> httpResult=new HttpResult<>();
        try {
//            System.out.println("这句话执行了没");
            signService.stopSign(courseId);
            //统计没有签到的学生名单并把他们插入缺勤表中
            //1.从CourseStudent 中选中  选了课程id 的学生id，
            //2.从SignRecordRepository 中选出所有的学生id
            //   在1 中出现，2中没出现的 就是缺勤学生
            List<CourseStudent> courseStudents=courseStudentService.findAll();
            List<SignRecorder> signRecorders=signRecorderService.findAll();
             System.out.println("我的值是: "+courseStudents.toString());
             System.out.println("我的值是: "+signRecorders.toString());
           Iterator iterator1= courseStudents.iterator();
           Iterator iterator2= signRecorders.iterator();
            LinkedList<CourseStudent> list=new LinkedList<>();
           while(iterator1.hasNext()){
               CourseStudent c1=(CourseStudent)iterator1.next();
               while(iterator2.hasNext()){
                  SignRecorder s1=(SignRecorder)  iterator2.next();
                  if((c1.getCourse_id().equals(s1.getCourseId()))){
                      iterator1.remove();
//                      list.add(c1);
                  }
               }

           }
            System.out.println("我的值是: "+courseStudents);
           //把 缺勤列表的迭代器装入 缺勤列表
            Iterator iterator3=courseStudents.iterator();
           while(iterator3.hasNext()){
               System.out.println("hellowrold");
               CourseStudent courseStudent2=(CourseStudent)iterator3.next();
               System.out.println("=====+"+courseStudent2);
               //保存到缺勤列表
               Queqin queqin =new Queqin();
               queqin.setCourseId(courseStudent2.getCourse_id());
               queqin.setStudentId(courseStudent2.getStudent_id());
                queqinService.save(queqin);
           }




            httpResult.setStatus("停止签到成功");
        }catch (Exception e){
            httpResult.setMessage("停止签到失败");
        }finally {
            return  httpResult;
        }

   }
//    @Column(name = "course_id")
//    private String courseId;//课程id
//    @Column(name = "student_id")
//    private String studentId;//学生id
//    @Column(name = "student_xuehao")
//    private String xuehao;//学号
//    @Column(name = "student_name")
//    private String name;//姓名
//    @Column(name = "sign_time")
//    private Date time;
    //学生签到
//    @PostMapping("/addSignRecorders")
@RequestMapping(value = "/addSignRecorders",method=RequestMethod.POST)
//    public HttpResult courseStudent(@ModelAttribute SignRecorder signRecorder) {
    public HttpResult courseStudent(@ModelAttribute SignRecorder signRecorder) {
        HttpResult result = new HttpResult();
        System.out.println("这句话显示了没有?");
        try {
            System.out.println(signRecorder);
            Sign sign=signService.findSignsByCourse(signRecorder.getCourseId());
            System.out.println(sign);
            String key=(signService.findSignsByCourse(signRecorder.getCourseId())).getSign_key();//根据课程号找到最新的Key
                System.out.println("key 的值为："+key);
                if(sign.isState()==false){
                    result.setMessage("该课程处于不可签到状态");
                    return  result;
                }
                if(!signRecorder.getKey().equals(sign.getSign_key())){
                    result.setMessage("签到码不正确，请输入正确的签到码");
                    return result;
                }
                if(sign.isState()&& signRecorder.getKey().equals(sign.getSign_key())){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
                    java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
                    signRecorder.setTime(date);
                    signRecorderService.save(signRecorder);
                    result.setMessage("签到成功");
                    result.setData(signRecorder);
                }

        }catch (Exception e){
            result.setStatus("签到失败");
        }finally {
            return  result;
        }
    }
    /*
     *
     * */
//   @PostMapping(value = "/course/{courseId}/sign")
//   public HttpResult add(@PathVariable Long courseId) {
//        HttpResult result = new HttpResult();
//        try {
//            if (signService.findSignsNotEndByCourse(courseId).size() != 0) {
//                throw new Exception("本课程有签到尚未结束，请先结束签到！");
//            }
//            Sign sign = new Sign();
//            sign.setEnd(false);
//            sign.setCourseId(courseId);
//            signService.save(sign);
//            result.setStatus("成功发起签到。");
//            result.setMessage("课程" + courseId.toString() + "发起了签到");
//        } catch (Exception e) {
//            if (!e.getMessage().isEmpty()) {
//                result.setMessage(e.getMessage());
//            }
//            result.setStatus("该课程处在可以签到的状态，不能重复发起签到。");
//        } finally {
//            return result;
//        }

//    }

    /*
     * 结束签到
     * */
/*  @PutMapping(value = "/sign/{id}/end")
   public HttpResult end(@PathVariable Long id) {

        HttpResult result = new HttpResult();
        try {
            if (signService.signIsEnd(id)) {
                throw new Exception("签到已经结束");
            }
            Sign sign = signService.findSignById(id);
            sign.setEnd(true);
            signService.save(sign);
            result.setStatus("本课程签到结束了。");
            result.setMessage("课程" + id.toString() + "结束了签到");
        } catch (Exception e) {
            if (!e.getMessage().isEmpty()) {
                result.setMessage(e.getMessage());
            }
            result.setStatus("本课程已经结束签到，无须重复结束。");
        } finally {
            return result;
        }

    }
*/

    /*
     * 查询课程所有发起的签到
     * */
//    @GetMapping(value = "/course/{courseId}/signs")
//    public HttpResult querySignsByCourse(@PathVariable Long courseId) {
//        HttpResult<List<Sign>> result = new HttpResult<>();
//        List<Sign> signs = signService.findSignsByCourse(courseId);
//        result.setData(signs);
//        result.setStatus("课程所有发起的签到：");
//        return result;
//    }

    //签到记录

//    @PostMapping("/addSignRecorders")
//    public HttpResult courseStudent(@ModelAttribute SignRecorder signRecorder) {
////        Long lcourseId = signRecorder.getCourseId();
////        Long lstudentId = signRecorder.getStudentId();
//        HttpResult result = new HttpResult();
//        return  result;
//    }
//        try {
//            if (courseStudentService.validCourse(lcourseId)) {
//                if (signService.signIsEnd(lcourseId)) {
//                    if (courseStudentService.isStudentOfCourse(lcourseId, lstudentId)) {
//                        if (signRecorderService.isSigned(lcourseId, lstudentId)) {
//                            result.setStatus(studentService.findStudentById(lstudentId).getName() + "已经签到。");
//                        } else {
//                            signRecorderService.save(signRecorder);
//                            result.setStatus(studentService.findStudentById(lstudentId).getName() + "签到课程《" + courseService.findCourseById(lcourseId).getName() + "》成功。");
//                        }
//                    }
//                } else {
//                    result.setStatus("该课程没有发起签到或者签到已经结束。");                }
//            } else {
//                result.setStatus("该课程无效。");
//            }
//        } catch (Exception e) {
//            result.setStatus("非法签到。");
//        } finally {
//            return result;
//        }
//    }

  /*
    @PostMapping(value = "/beginsign",params = {"courseId"})
    public HttpResult beginsign(Long courseId)  {

        HttpResult result = new HttpResult();
        try {
            if (signService.findSignsNotEndByCourse(courseId).size() != 0) {
                throw new Exception("本课程有签到尚未结束，请先结束签到！");
            }
            Sign sign = new Sign();
            sign.setEnd(false);
            sign.setCourseId(courseId);
            signService.save(sign);
            result.setStatus("成功发起签到。");
            result.setMessage("课程" + courseId.toString() + "发起了签到");
        } catch (Exception e) {
            if (!e.getMessage().isEmpty()) {
                result.setMessage(e.getMessage());
            }
            result.setStatus("该课程处在可以签到的状态，不能重复发起签到。");
        } finally {
            return result;
        }


    }
*/
  /*
    @PostMapping(value = "/endsign",params = {"courseId"})
    public HttpResult endsign(Long courseId) {
        HttpResult result = new HttpResult();
        try {
            if (signService.signIsEnd(courseId)) {
                result.setStatus("签到已经结束");
            }
           Sign  sign = signService.findSignById(courseId);
            sign.setEnd(true);

            signService.save(sign);
            result.setStatus("本课程成功结束了签到。");
            result.setMessage("课程" + courseId.toString() + "结束了签到");
        } catch (Exception e) {
            if (!e.getMessage().isEmpty()) {
                result.setMessage(e.getMessage());
            }
            result.setStatus("本课程已经结束签到，无须重复结束；或者尚未发起签到。");
        } finally {
            return result;
        }


    }
*/



}
